import {ref, computed} from "vue";

/**
 * @description 表格多选数据操作
 * @param {String} rowKey 当表格可以多选时，所指定的 id
 * @param {Array} selectList 默认选中的数据行
 * */
export const useSelection = (rowKey: string = "id", selectList: any[] = []) => {
  const isSelected = ref<boolean>(false);
  const selectedList = ref<{ [key: string]: any }[]>([]);

  // 当前选中的所有 ids 数组
  const selectedListIds = computed((): string[] => selectedList.value.map(item => item[rowKey]));

  /**
   * @description 多选操作
   * @param {Array} rowArr 当前选择的所有数据
   * @return void
   */
  const selectionChange = (rowArr: { [key: string]: any }[]) => {
    rowArr.length ? (isSelected.value = true) : (isSelected.value = false);
    selectedList.value = rowArr;
  };

  /**
   * 处理单行勾选/取消勾选
   * @param rowArr
   * @param row
   */
  const handleSelect = (rowArr: any[], row: any) => {
    const checked = rowArr.some(item => item[rowKey] == row[rowKey]);
    if (selectList.length) {
      if (!checked) {
        const index = selectList.findIndex(selectItem => selectItem[rowKey] == row[rowKey]);
        selectList.splice(index, 1);
      } else {
        const exists = selectList.some(item => item[rowKey] == rowKey);
        if (!exists) {
          selectList.push(row);
        }
      }
    } else {
      selectList = rowArr;
    }
    selectList.length === 0 ? (isSelected.value = false) : (isSelected.value = true);
    selectedList.value = JSON.parse(JSON.stringify(selectList));
  };

  /**
   * 处理全选/取消全选
   * @param rowArr
   * @param tableData
   */
  const handleSelectAll = (rowArr: any[], tableData: any[]) => {
    if (!selectList.length) {
      rowArr.length === 0 ? (isSelected.value = false) : (isSelected.value = true);
      selectedList.value = rowArr;
      return;
    }
    if (rowArr.length) {
      rowArr.forEach((row: any) => {
        const exists = selectList.some(item => item[rowKey] == row[rowKey]);
        if (!exists) {
          selectList.push(row);
        }
      });
    } else {
      tableData.forEach((row: any) => {
        const index = selectList.findIndex(selectItem => selectItem[rowKey] == row[rowKey]);
        if (index > -1) {
          selectList.splice(index, 1);
        }
      });
    }
    selectList.length === 0 ? (isSelected.value = false) : (isSelected.value = true);
    selectedList.value = JSON.parse(JSON.stringify(selectList));
  };

  return {
    isSelected,
    selectedList,
    selectedListIds,
    selectionChange,
    handleSelect,
    handleSelectAll,
  };
};
